<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;

/**
 * @property mixed followings
 * @property mixed name
 * @property mixed id
 */
class User extends Authenticatable{

	use Notifiable;

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'name', 'email', 'password',
	];

	/**
	 * The attributes that should be hidden for arrays.
	 *
	 * @var array
	 */
	protected $hidden = [
		'password', 'remember_token',
	];

	/**
	 * The attributes that should be cast to native types.
	 *
	 * @var array
	 */
	protected $casts = [
		'email_verified_at' => 'datetime',
	];

	/**
	 * 用户的gravatar 头像
	 *
	 * @param string $size
	 * @return string
	 */
	public function gravatar($size = '100'){
		$hash = md5(strtolower(trim($this->attributes['email'])));
		return "http://www.gravatar.com/avatar/$hash?s=$size";
	}

	public static function boot(){
		parent::boot(); // TODO: Change the autogenerated stub

		static::creating(function($user){
			$user->activation_token = Str::random(10);
		});
	}

	/**
	 * 关联微博
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	public function statues(){
		return $this->hasMany(Status::class);
	}

	/**
	 * 关联粉丝
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function followers(){
		return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id');
	}

	/**
	 * 关联的用户关注人
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function followings(){
		return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
	}

	/**
	 * 所有的微博数据
	 *
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	public function feed(){
		$follow_ids=$this->followings->pluck('id')->toArray();
		array_push($follow_ids,$this->id);
		return Status::whereIn('user_id',$follow_ids)->with('user')->orderBy('created_at','desc');
	}

	/**
	 * 关注用户
	 *
	 * @param $user_ids
	 */
	public function follow($user_ids){
		if(!is_array($user_ids)){
			$user_ids = compact('user_ids');
		}
		$this->followings()->sync($user_ids, false);
	}

	/**
	 * 取消关注
	 *
	 * @param $user_ids
	 */
	public function unfollow($user_ids){
		if(!is_array($user_ids)){
			$user_ids = compact('user_ids');
		}
		$this->followings()->detach($user_ids);
	}

	/**
	 * 是否关注用户
	 *
	 * @param $user_id
	 * @return mixed
	 */
	public function isFollowing($user_id){
		return $this->followings->contains($user_id);
	}

}
